package com.cskaoyan.order.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cskaoyan.mall.commons.result.ResponseData;
import com.cskaoyan.mall.commons.result.ResponseUtil;
import com.cskaoyan.order.dto.OrderDetailResponse;
import com.cskaoyan.order.dto.OrderListResponse;
import com.cskaoyan.order.form.CreateOrderRequest;
import com.cskaoyan.order.service.OrderCoreService;
import com.cskaoyan.order.service.OrderQueryService;
import com.cskaoyan.order.utils.GlobalIdGeneratorUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.concurrent.ExecutionException;

@RestController
@RequestMapping("shopping")
public class OrderController {

    @Autowired
    OrderCoreService orderCoreService;

    @PostMapping("order")
    public ResponseData order(@RequestBody CreateOrderRequest request, HttpServletRequest servletRequest) throws IOException, ExecutionException, InterruptedException {
        String token = servletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(token);
        Long uid = Long.parseLong(object.get("uid").toString());

        request.setUserId(uid);

        String orderId = orderCoreService.createOrder(request);
        return new ResponseUtil().setData(orderId,null);
    }

    @GetMapping("order")
    public ResponseData orderList(Integer page, Integer size, String sort,HttpServletRequest servletRequest) {

        String token = servletRequest.getHeader("user_info");
        JSONObject object = JSON.parseObject(token);
        Long uid = Long.parseLong(object.get("uid").toString());

        OrderListResponse orderListResponse = orderCoreService.selectOrderList(page,size,sort,uid);

        return new ResponseUtil().setData(orderListResponse,null);
    }


    //下面都是小龙虾的
    @Autowired
    OrderQueryService orderQueryService;



    @GetMapping("/order/{id}")
    public ResponseData getOrderDetail(@NotNull @PathVariable String id){
        OrderDetailResponse orderDetailResponse = orderQueryService.orderDetail(id);
        return new ResponseUtil().setData(orderDetailResponse,"success");
    }

    @PostMapping("/cancelOrder")
    public ResponseData cancleOrder(@RequestBody String orderId){
        JSONObject orderId1 = JSON.parseObject(orderId);
        Long orderId2 = Long.parseLong(orderId1.get("orderId").toString());
        orderCoreService.cancelOrder(orderId2.toString());
        return new ResponseUtil<>().setData("成功","success");
    }

    @DeleteMapping("/order/{id}")
    public ResponseData deleteOrder(@NotNull @PathVariable Long id){
        orderCoreService.deleteOrder(String.valueOf(id));
        return new ResponseUtil<>().setData("成功","success");
    }

}
